﻿namespace Probel.Client.Commands
{
    using System;
    using System.ComponentModel;

    using Probel.Client.StatReaderReference;

    [Command("stat", "s", "stat |-d [date] Displays usage statistics.")]
    public class StatCommand : ICommand
    {
        #region Methods

        public void Execute(dynamic context)
        {
            var proxy = context.ProxyReader as IStatReader;
            var args = context.Arguments as string[];

            Console.Write("Getting statistics");
            var result = Execute(proxy, args);
            Console.WriteLine(" Done");
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Statistics (application count): ");
            Console.ResetColor();
            Console.WriteLine();
            Console.WriteLine("nDoctor light: {0,-3}", result.LdocCount);
            Console.WriteLine("      nDoctor: {0,-3}", result.NDoctorCount);
            Console.WriteLine("        Other: {0,-3}", result.OtherCount);
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Windows versions:");
            Console.ResetColor();
            Console.WriteLine();

            int i = 0;
            foreach (var version in result.WindowsNames)
            {
                Console.WriteLine("   {0,-2} - {1,4} item(s) on '{2}'", ++i, version.Count, version.Name);
            }
        }

        private static ApplicationsSummary Execute(IStatReader proxy, string[] args)
        {
            ApplicationsSummary result = null;
            if (args.Length > 1 && !args[0].Trim().StartsWith("d")) { throw new NotSupportedException("The arguments are not valid"); }
            if (args.Length == 1)
            {
                args[0] = args[0].Trim().Replace("d", "");
                var date = DateTime.Parse(args[0]);

                Console.Write(" before {0}...", date.ToShortDateString());
                result = proxy.GetApplicationsSummaryBefore(date);
            }
            else
            {
                Console.Write("...");
                result = proxy.GetApplicationsSummary();
            }
            return result;
        }

        #endregion Methods
    }
}